<?php
class advertiseController extends Controller{
	public function index(){
		$p = G('p') ? G('p') : 1;
		$total = $this->model->count_advertises();
		$itemPerPage = 15;
		$page = load_util('Page');
		$pages = $page->init(array('currentPage'=>$p,'totalItems'=>$total,'itemPerPage'=>$itemPerPage));
		if( $pages ){
			$this->assign('pages', $pages);
			$start = ($p-1)*$itemPerPage;
			$limit = $start .','. $itemPerPage;
			$list = $this->model->get_advertises('','',$limit);
		}else{
			$list = $this->model->get_advertises();
		}
		if( DEBUG ){
			dump($list);
			dump($this->model->sql);
		}
		$this->assign('list', $list);
		$this->display('admin/advertises.html');
	}

	public function add(){
		$upload = load_util('Upload');
		$upload->config(array(
				'save_path' => __UPLOAD__.'advertise/',
				'safe_ext' => array('jpg','jpeg','gif','png'),
				));
		$upRs = $upload->save();
		$data = get_data();
		$data['attachment'] = $upload->saveName;
		$rs = $this->model->add($data);
		if( is_int($rs) && $rs>0 ){
			$this->assign('status',1);
			//tips('添加成功!',1,0,__URL__.'index.php?advertise');
		}else{
			$this->assign('status',0);
			//tips('添加失败',0,0,__URL__.'index.php?advertise');
		}
	}

	public function edit(){
		if( G('save')==1 ){
			$data = get_data();
			$rs = $this->model->edit($data['id'],$data);
			if( is_int($rs) && $rs>0 ){
				ajax_return(array('status'=>1));
			}else{
				ajax_return(array('status'=>0)); 
			}
			exit;
		}
	}

	public function del(){
		$id = intval(G('id'));
		if( empty($id) ){
			ajax_return(array('status'=>0));
			exit;
		}
		$rs = $this->model->del($id);
		ajax_return(array('status'=>$rs));
		exit;
	}

	public function upload(){
		$upload = load_util('Upload');	
		$config = array(
			'save_path'=> __UPLOAD__.'advertise/'
			);	
		$upload->config($config);
		$rs = $upload->save();
		if( $rs!==false ){
			$rs = json_decode($rs,true);
			$file = UPLOAD_URL.'advertise/'.$rs[0]['saveName'];
			$state = "SUCCESS";
			echo "{url:'".$file."',title:'".$rs[0]['saveName']."',state:'".$state."'}";
		}else{
			$state = "FAILED ".$upload->get('error');
			echo "{url:'".$file."',title:'".$title."',state:'".$state."'}";
		}
	}
	
}
